package pattern.creational.singleton;

import java.io.Serializable;

/**
 * 饿汉式
 *
 * @Author Gavin
 * @date 2020.07.15 16:38
 */
public class HungrySingleton implements Serializable {
    private final static HungrySingleton hungrySingleton;

    static {
        hungrySingleton = new HungrySingleton();
    }

    private HungrySingleton() {
        if (hungrySingleton != null) {
            throw new RuntimeException("单例构造器禁止反射调用。");
        }
    }

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    //该方法能后避免序列化后反序列化时候破环单例的情况
    //因为反序列话是通过反射来生产对象的，通过反射会破环单例，导致生成的对象不一致
    public Object readResolve() {
        return hungrySingleton;
    }
}
